import {View, Text, StyleSheet, Image, TouchableOpacity} from 'react-native'
import React, {Component} from 'react'
import {padding, default as styles, rectWithSize, HUNDRED_PERCENT, border} from "../../../../style";
import {Actions} from "react-native-router-flux";
import {
    FeatureBtnInterface, getStatusLabel,
    ORDER_COMPLETED,
    WAIT_PAY,
    WAIT_RECEIPT
} from "./orderListFeatureBtnConfig";
import CommonFlatList from "../../../common/CommonFlatList";
import {
    defaultArr,
    defaultPage,
    getAssetUrl,
    getTime,
    keyExtractor,
    numberWithDefault,
    PromiseWrapper
} from "../../../../util";
import {inject, observer} from "mobx-react/custom";
import {OrderStore} from "../../../../store/modules/order";
import {Store} from "../../../../store";
import {
    OrderModelInterface,
    PageInterface,
    ProductOrderRelationInterface
} from "../../../../net/instance/CommenModelInstance";
import toast from "../../../common/ToastProxy";
import FastImageCustom from "../../../widget/FastImageCustom";
import * as _ from 'lodash'
import {alertProxy} from "../../../common/AlertProxy";

interface OrderListProps extends Store {
    index: number,
    status: number,
    tabLabel: string
}

interface OrderListState {
    page: PageInterface,
    orderList: OrderModelInterface[],
    count: number
}

export default class OrderListWrapper extends Component<OrderListProps, OrderListState> {


    refresh() {
        const orderList: any = this.refs["orderList"];
        const instance: OrderList = orderList.wrappedInstance;
        instance.refresh();
    }


    render() {
        return <OrderList {...this.props} ref={"orderList"}/>
    }
}

enum ActionTag {
    REFRESH, LOADMORE
}

/***
 */
@inject("order", "user")
@observer
class OrderList extends Component<OrderListProps, OrderListState> {
    order: OrderStore;
    commonFlatList: CommonFlatList;
    loadingPage = false;


    state = {
        page: defaultPage,
        orderList: defaultArr,
        count: 0,
    };

    constructor(props: OrderListProps) {
        super(props);
        this.order = this.props.order;
    }

    /***
     * 获取当前tab的列表数据
     * @param action 刷新或者加载更多
     */
    getOrderListData = async (action: ActionTag) => {
        const userId = this.props.user.user.id;
        //获取到本次加载的数据
        const data = await this.order.getOrderList(this.state.page, userId, this.props.status);

        //将本次获取到的数据赋值给当前页面的列表
        let orderList = defaultArr;
        const rows = _.cloneDeep(data.rows);
        if (action === ActionTag.REFRESH) {
            orderList = rows;
        } else {
            orderList = this.state.orderList.concat(rows);
        }
        //使当前函数变成异步的 后面的函数都会在更新了orderList和count后执行
        await PromiseWrapper(resolve => {
            this.setState({
                orderList,
                count: data.count
            }, () => {
                resolve()
            })
        });
    };


    /***
     * 根据订单状态渲染相应按钮
     */
    computedFeatureBtnArr(orderStatus: number = 1): FeatureBtnInterface[] {
        switch (orderStatus) {
            case 1:
                return WAIT_PAY;
            case 2:
                return WAIT_RECEIPT;
            case 3:
                return ORDER_COMPLETED;
        }
    }


    /***
     * 根据一组订单商品获取总价
     */
    getSectionTotalPrice(products: ProductOrderRelationInterface[]) {
        return products.reduce((pre, cur) => {
            const count = cur.relation.count || 1;
            return count * cur.price + pre;
        }, 0);
    }


    /***
     * 刷新tab数据
     * loadingPage为true不触发
     * 调用getOrderListData
     */
    refresh = async () => {
        if (!this.loadingPage) {
            this.setState({
                page: defaultPage
            }, async () => {
                this.loadingPage = true;
                await this.getOrderListData(ActionTag.REFRESH);
                const {orderList, count} = this.state;
                this.commonFlatList.refreshComplete(orderList.length !== count);
                this.loadingPage = false;
            });
        }
    };


    /***
     * loadingPage为true时不触发
     * 列表值为最大值时不触发
     * 触发后调用getOrderListData
     */
    loadMore = async () => {
        let {orderList, count} = this.state;
        if (orderList.length !== count && !this.loadingPage) {
            //翻页时会自动设置loadingPage为true
            await this.changePage();
            await this.getOrderListData(ActionTag.LOADMORE);
            let {orderList, count} = this.state;
            this.commonFlatList.loadMoreComplete(orderList.length !== count);
            this.loadingPage = false;
        }
    };

    /***
     * 当loadingPage为true时不能翻页，加载时不能翻页
     * 改方法是一个异步方法 必须等待state变化完后执行
     */
    changePage = async () => {
        if (!this.loadingPage) {
            this.loadingPage = true;
            const page = this.state.page;
            return PromiseWrapper((resolve) => {
                this.setState({
                    page: {
                        ...page,
                        pageNum: page.pageNum + 1
                    }
                }, () => resolve());
            })
        }
    };

    //渲染订单功能按钮
    renderFeatureBtn(order: OrderModelInterface) {
        //功能按钮
        const featureBtns = this.computedFeatureBtnArr(order.status);
        const callback = () => {
            const orderStatus = order.status;
            if (orderStatus === 1 || orderStatus === 2 || orderStatus === 4) {
                this.commonFlatList._refresh();
            } else if (orderStatus === 3) {
                Actions.push("Evaluation", {orderData: order});
            }
        };

        return (<View style={[{marginTop: 12}, OrderListStyle.rowStyle]}>
            {
                featureBtns && featureBtns.map(({text, onPress}, index) => {
                    return (<TouchableOpacity onPress={onPress(order, callback)}
                                              key={index}
                                              style={[padding(7, 12), border(1, "#E0E0E0"), {
                                                  marginLeft: 10,
                                                  borderRadius: 3
                                              }]}>
                        <Text style={OrderListStyle.btnFont}>{text}</Text>
                    </TouchableOpacity>)
                })

            }
        </View>)
    }

    renderSection = ({item}) => {
        const orderItem: OrderModelInterface = item;
        const {createTime, products, status, actuallyPaid} = orderItem;
        return (
            <View style={[{marginTop: 10, backgroundColor: "#fff"}, padding(12, 13)]}>
                <View
                    style={[{marginBottom: 13}, OrderListStyle.rowStyle]}>
                    <Text style={OrderListStyle.normalFont}>订单号：{getTime(createTime)}</Text>
                    <Text style={OrderListStyle.normalFont}>{getStatusLabel(status)}</Text>
                </View>
                {products.map(({imageUrl, infoImageUrl, id, name, price, relation}, index) => {
                    const isLast = products.length - 1 === index;
                    return <View key={id}
                                 style={[OrderListStyle.borderCell, padding(13, 0), {
                                     height: 80,
                                     borderBottomWidth: isLast ? 1 : 0
                                 }, OrderListStyle.rowStyle]}>
                        <FastImageCustom style={rectWithSize(60)} source={{uri: getAssetUrl(infoImageUrl)}}/>
                        <View style={[{
                            flex: 1,
                            height: HUNDRED_PERCENT,
                            marginLeft: 17,
                            marginRight: 27,
                        }]}>
                            <Text style={[OrderListStyle.normalFont]}
                                  numberOfLines={1}>{name}</Text>
                        </View>
                        <View style={[{height: HUNDRED_PERCENT}, styles.justifyBetween]}>
                            <Text style={OrderListStyle.normalFont}>￥{price}</Text>
                            <Text style={[OrderListStyle.miniFont]}>数量:{relation.count || 1}件</Text>
                        </View>
                    </View>
                })}
                <View style={[{marginTop: 12}, styles.alignItemsEnd]}>
                    <Text style={[OrderListStyle.minFont, {textAlignVertical: "bottom"}]}>合计:<Text
                        style={[OrderListStyle.priceFont, {marginLeft: 3}]}>￥{numberWithDefault(actuallyPaid)}</Text></Text>
                    {this.renderFeatureBtn(orderItem)}
                </View>
            </View>
        )
    };

    render() {
        return (<CommonFlatList refresh={this.refresh} data={this.state.orderList}
                                renderItem={this.renderSection}
                                ref={commonFlatList => this.commonFlatList = commonFlatList}
                                keyExtractor={keyExtractor} loadMore={this.loadMore} style={OrderListStyle.container}>
        </CommonFlatList>)
    }
}

const OrderListStyle = StyleSheet.create({
    container: {flex: 1, backgroundColor: "#EFEFEF"},
    rowStyle: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center"
    },
    normalFont: {
        fontSize: 12,
        color: "#333"
    }, btnFont: {
        fontSize: 14,
        color: "#333"
    }, miniFont: {
        fontSize: 10,
        color: "#999"
    }, minFont: {
        fontSize: 12,
        color: "#999"
    }, priceFont: {
        fontSize: 14,
        color: "#D0021B"
    },
    borderCell: {
        borderColor: "#EFEFEF",
        borderTopWidth: 1,
    }
});

 